package com.jckl.foodathon.restlet.services;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;

import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.Point;
import com.google.appengine.api.datastore.GeoPt;
import com.google.gson.Gson;
import com.jckl.foodathon.common.util.GeoLocation;
import com.jckl.foodathon.dao.LocationServiceDAO;
import com.jckl.foodathon.model.Coordinate;
import com.jckl.foodathon.restlet.clients.GoogleGeocodingClient;


/**
 * Resource which has only one representation.
 * 
 */
public class GeoCodingResource extends ServerResource {
	
	private static final Logger log = Logger.getLogger(GeoCodingResource.class.getName());

    @Put("json")
    public String findLocality(Representation entity) {
    	
    	String returnString = "";
    	try{
    		JSONObject req = (new JsonRepresentation(entity)).getJsonObject();
    		Gson gson = new Gson();
    		
    		Coordinate coordinate = gson.fromJson(req.toString(), Coordinate.class);
    		
    		GoogleGeocodingClient ggc = new GoogleGeocodingClient();
			returnString = ggc.getLocality(coordinate.getLatitude(), coordinate.getLongitude());
			coordinate.setLocality(returnString);

			GeoLocation geoLocation = new GeoLocation();
			coordinate.setPoint(geoLocation.getGeoPt(coordinate.getLatitude(), coordinate.getLongitude()));
			coordinate.setQueryDate(new Date());
			coordinate.setGeoCells(geoLocation.getGeoCells(coordinate.getLatitude(), coordinate.getLongitude()));
			
			//Store locality query into datasource
			LocationServiceDAO locationDao = new LocationServiceDAO();
			locationDao.newLocalityQuery(coordinate);

    	}catch(JSONException jsonEx){
    		jsonEx.printStackTrace();
    	}catch(IOException ioEx){
    		ioEx.printStackTrace();
    	}
		return returnString;
    }
    
    @Get
    public String testAddress(){
    	String returnString = "";
		GoogleGeocodingClient ggc = new GoogleGeocodingClient();
		returnString = ggc.getLocality(3.0265062, 101.6912763);
		
		Coordinate coordinate = new Coordinate(3.0265062, 101.6912763, "");
		
		LocationServiceDAO locService = new LocationServiceDAO();
		List<Coordinate> coordinates = locService.getNearbyCoordinate(coordinate, 50, 0);
		
		returnString = new Gson().toJson(coordinates);
		return returnString;
    }
    
}
